package com.findsing.jetty.websocket.server.config;

import java.util.Arrays;
import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import com.findsing.jetty.websocket.async.AsyncProcesser;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.findsing.jetty.websocket.controller")
public class ServletConfig extends WebMvcConfigurerAdapter{
	
	/**
	 * We want every request coming to URL starting with "/images" to be served with contents of "/webapp/images" directory
	 */
	@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("images/**").addResourceLocations("images/");
        registry.addResourceHandler("/**").addResourceLocations("/");
    }
	
	@Bean
	public InternalResourceViewResolver getInternalResourceViewResolver()
	{
		InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
		internalResourceViewResolver.setPrefix("/jsp/view");
		internalResourceViewResolver.setSuffix(".jsp");
		internalResourceViewResolver.setViewClass(org.springframework.web.servlet.view.JstlView.class);
		return internalResourceViewResolver;
	}
	
	@Bean
	public AsyncProcesser getAsyncProcesser(){
		return new AsyncProcesser();
	}
	
	@Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		converters.add(getHttpMessageConverter());
        super.configureMessageConverters(converters);
    }
	
    private HttpMessageConverter<Object> getHttpMessageConverter() {
        HttpMessageConverter<Object> converter = new MappingJackson2HttpMessageConverter();
        ((AbstractHttpMessageConverter<Object>) converter).setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON));
        return converter;
    }
}
